document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('scratchCanvas');
    const ctx = canvas.getContext('2d');
    
    let isDrawing = false;
    
    // 设置画布尺寸以匹配父容器
    canvas.width = canvas.parentElement.offsetWidth;
    canvas.height = canvas.parentElement.offsetHeight;

    // 绘制刮刮层
    function drawScratchLayer() {
        ctx.fillStyle = '#C0C0C0'; // 灰色涂层
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#fff';
        ctx.font = '24px sans-serif';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('刮一刮', canvas.width / 2, canvas.height / 2);
    }

    // 鼠标按下事件
    function handleMouseDown(e) {
        isDrawing = true;
        scratch(e.offsetX, e.offsetY);
    }
    
    // 鼠标移动事件
    function handleMouseMove(e) {
        if (!isDrawing) return;
        scratch(e.offsetX, e.offsetY);
    }
    
    // 鼠标释放事件
    function handleMouseUp() {
        isDrawing = false;
    }

    // 刮开涂层
    function scratch(x, y) {
        ctx.globalCompositeOperation = 'destination-out'; // 设置为擦除模式
        ctx.lineWidth = 30; // 笔触宽度
        ctx.lineJoin = 'round';
        ctx.lineCap = 'round';

        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.lineTo(x + 1, y + 1); // 绘制一个非常小的线条来模拟点
        ctx.stroke();
    }

    // 绑定事件监听器
    canvas.addEventListener('mousedown', handleMouseDown);
    canvas.addEventListener('mousemove', handleMouseMove);
    canvas.addEventListener('mouseup', handleMouseUp);
    canvas.addEventListener('mouseleave', handleMouseUp); // 鼠标移出画布也停止绘制

    // 移动端支持
    canvas.addEventListener('touchstart', (e) => {
        e.preventDefault();
        const touch = e.touches[0];
        const rect = canvas.getBoundingClientRect();
        handleMouseDown({ offsetX: touch.clientX - rect.left, offsetY: touch.clientY - rect.top });
    });

    canvas.addEventListener('touchmove', (e) => {
        e.preventDefault();
        const touch = e.touches[0];
        const rect = canvas.getBoundingClientRect();
        handleMouseMove({ offsetX: touch.clientX - rect.left, offsetY: touch.clientY - rect.top });
    });

    canvas.addEventListener('touchend', handleMouseUp);

    // 初始化
    drawScratchLayer();
});